package com.example.file_management.controller;

import com.example.file_management.pojo.material.SelfCheck;
import com.example.file_management.service.SelfCheckService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/self-checks")
@CrossOrigin(origins = "http://localhost:5173")
public class SelfCheckController {

    private final SelfCheckService selfCheckService;

    @Autowired
    public SelfCheckController(SelfCheckService selfCheckService) {
        this.selfCheckService = selfCheckService;
    }

    // 插入自检记录
    @PostMapping
    public ResponseEntity<SelfCheck> insertSelfInspection(@RequestBody SelfCheck selfCheck) {
        int result = selfCheckService.insertSelfInspection(selfCheck);
        if (result > 0) {
            return ResponseEntity.ok(selfCheck);
        } else {
            return ResponseEntity.badRequest().build();
        }
    }

    // 根据任务ID查询自检记录
    @GetMapping("/task/{taskId}")
    public ResponseEntity<List<SelfCheck>> getSelfInspectionsByTaskId(@PathVariable int taskId) {
        List<SelfCheck> selfChecks = selfCheckService.getSelfInspectionsByTaskId(taskId);
        if (selfChecks != null && !selfChecks.isEmpty()) {
            return ResponseEntity.ok(selfChecks);
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    // 更新自检记录
    @PutMapping("/{selfCheckId}")
    public ResponseEntity<SelfCheck> updateSelfInspection(@PathVariable int selfCheckId, @RequestBody SelfCheck selfCheckDetails) {
        SelfCheck selfCheck = (SelfCheck) selfCheckService.getSelfInspectionsByTaskId(selfCheckId);
        if (selfCheck != null) {
            selfCheck.setCheckName(selfCheckDetails.getCheckName());
            selfCheck.setCheckDescription(selfCheckDetails.getCheckDescription());
            selfCheck.setCheckStatus(selfCheckDetails.getCheckStatus());
            selfCheck.setCheckDate(selfCheckDetails.getCheckDate());
            int result = selfCheckService.updateSelfInspection(selfCheck);
            if (result > 0) {
                return ResponseEntity.ok(selfCheck);
            } else {
                return ResponseEntity.badRequest().build();
            }
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    // 根据自检ID删除自检记录
    @DeleteMapping("/{selfCheckId}")
    public ResponseEntity<Void> deleteSelfInspection(@PathVariable int selfCheckId) {
        int result = selfCheckService.deleteSelfInspection(selfCheckId);
        if (result > 0) {
            return ResponseEntity.ok().build();
        } else {
            return ResponseEntity.notFound().build();
        }
    }
}